package fun.ipconfig.service;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.List;

public class Transformer implements ClassFileTransformer {
    private static List<Handel> handels = new ArrayList<>();
    private String packageName = null;
    private static Thread thread;
    public Transformer() {
        reload();
    }

    public Transformer(String packageName) {
        this.packageName = packageName;
        reload();
        if (packageName != null) {
            System.out.println("lisent-package: " + packageName);
        }
    }

    static void reload() {
        try {
            Transformer.thread = new Thread(() -> {
                while (true) {
                    try {
                        handels.stream().filter(handel->!handel.isIngrest()).forEach((handel)->{
                            handel.upFile();
                        });
                        Thread.sleep(2000);
                    } catch (Exception e) {
                    }
                }
            });
            thread.setName("agent-hot-thread");
            thread.setDaemon(true);
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public byte[] transform(ClassLoader loader,
            String className,
            Class<?> classBeingRedefined,
            ProtectionDomain protectionDomain,
            byte[] classfileBuffer) throws IllegalClassFormatException {
        String name = className.replaceAll("/", ".");
        if(loader != null && !name.startsWith("org.apache.catalina")){
            if (packageName == null) {
                handels.add(new Handel(loader, name));
            } else if (name.startsWith(packageName)) {
                handels.add(new Handel(loader, name));
            }
        }
        return classfileBuffer;
    }

}
